<?php
namespace app\common\controller\storage;

use Exception;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

/**
 * 七牛云对象存储 Kodo
 */
class QiniuKodo extends Upload
{
	/**
	 * 上传文件到阿里云OSS
	 */
	public function upload($name)
	{
		// $data = [
		// 	// Access Key ID
		// 	'accessKey' => 'l_OnndRIVj17ZwIKMOZBLorh5dK4BKI8WM0lRzoN',  
		// 	// Access Key Secret
		// 	'secretKey' => '7fXF7wbOWcC5pUJKmGz3N8DU6ZB7u3eehDJWHFe7',
		// 	// Bucket名称
		// 	'bucket'    => 'chenduxiu',
		// 	// 访问域名
		// 	'domain'    => 'https://test.itqaq.com',
		// ];
		// 配置参数
		// $bucket    = $data['bucket'];
		// $domain    = $data['domain'];
		// $accessKey = $data['accessKey'];
		// $secretKey = $data['secretKey'];

		$bucket    = $this->storageConfig['bucket'];
		$domain    = $this->storageConfig['domain'];
		$accessKey = $this->storageConfig['accessKey'];
		$secretKey = $this->storageConfig['secretKey'];
		
		// 获取 \think\File 对象
		$file = $this->isUpload($name);
		// 判断是否有文件上传
		if ( ! $file instanceof \think\File ) return $file;

		// 将文件上传到阿里云
		try {
			// 初始化鉴权对象
			$auth      = new Auth($accessKey, $secretKey);
			// 生成上传Token
			$token     = $auth->uploadToken($bucket);
			// 上传管理类 构建UplaodManager对象
			$uploadMgr = new UploadManager();
			// 文件在存储空间中的存放位置
			$path = $this->buildSaveName($file);
			// 执行文件上传到七牛云
			$info = $uploadMgr->putFile($token, $path, $file->getRealPath());
			// 文件URL地址
			$url = $domain . '/' . $info[0]['key'];
		} catch (Exception $e) {
			return $this->fail($e->getMessage());
		}
		// 文件上传成功
		return $this->achieve($url);
	}
}
